import zipfile
import os

def backupToZip(folder):
    folder = os.path.abspath(folder)

    number =1
    #检查文件是否存在 存在 则+1 否则跳出循环并创建
    while True:
        zipFilename = os.path.basename(folder)+'_'+str(number)+'.zip'
        if not os.path.exists(zipFilename):
            break
        number += 1

    print('Creating %s'%(zipFilename))
    #创建zip对象
    backupZip = zipfile.ZipFile(zipFilename,'w')

    #遍历文件夹中要压缩的内容
    for foldername, subfolders, filenames in os.walktree(folder):
        #将文件夹添加到压缩文件中
        backupZip.write(foldername)

        #将文件添加到压缩包中
        for filename in filenames:
            newBase = os.path.basename(folder)+'_'
            if filename.startswith(newBase) and filename.endswith('.zip'):
                continue
            backupZip.write(os.path.join(foldername,filename))
    
    backupZip.close()

    print('done')


backupToZip('D://MyPythonScript//folder')
